package cn.witque.controller;


import cn.witque.pojo.ItripUser;
import cn.witque.pojo.dto.Dto;
import cn.witque.pojo.vo.UserVo.TokenVo;
import cn.witque.service.TokenSevice;
import cn.witque.service.UserService;
import cn.witque.service.impl.TokenServiceImpl;
import cn.witque.utils.DtoUtil;
import cn.witque.utils.Md5Util;
import com.github.qcloudsms.httpclient.HTTPException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Map;

/**
 * @author jyk
 */
@Controller
@ApiModel
@RequestMapping("/api")
public class UserController {


    @Resource
    private UserService userService;

    @Resource
    private TokenSevice tokenSevice;


    /**
     * 注册
     * @return
     */
    @ApiOperation(value = "邮箱注册用户")
    @RequestMapping(value ="/doregister",method = RequestMethod.POST)
    @ResponseBody
    public Dto registUser(@RequestBody Map<String,String> map){

        ItripUser itripUser = regist(map.get("userCode"),map.get("userPassword"),map.get("userPassword"));
        userService.sendMail(map.get("userCode"));
        return userService.registUser(itripUser);
    }

    @ApiOperation(value = "手机注册用户")
    @RequestMapping(value ="/registerbyphone",method = RequestMethod.POST)
    @ResponseBody
    public Dto registUserByphone(@RequestBody Map<String,String> map){

        ItripUser itripUser = regist(map.get("userCode"),map.get("userPassword"),map.get("userPassword"));
        try {
            userService.sendPhoneMsg(map.get("userCode"));
        } catch (HTTPException e) {
            e.printStackTrace();
            return DtoUtil.getFailed("发送短信出现异常，请联系管理员","110");
        } catch (IOException e) {
            e.printStackTrace();
            return DtoUtil.getFailed("发送短信出现异常，请联系管理员","110");
        }
        return userService.registUser(itripUser);
    }



    /**
     * 激活用户
     * @param user
     * @param code
     * @return
     */

    @ApiOperation(value = "激活手机用户")
    @RequestMapping(value = "/validatephone",method = RequestMethod.PUT)
    @ResponseBody
    public Dto activeUserByPhone(@RequestParam String user,@RequestParam String code){
        return userService.AvtiveUser(user,code);
    }

    @ApiOperation(value = "激活邮箱用户")
    @RequestMapping(value = "/activate",method = RequestMethod.PUT)
    @ResponseBody
    public Dto activeUserByMail(@RequestParam String user,@RequestParam String code){
        return userService.AvtiveUser(user,code);
    }

    /**
     * 登录
     * @param name
     * @param password
     * @return
     */
    @ApiOperation(value = "登录")
    @RequestMapping(value = "/dologin",method = RequestMethod.POST)
    @ResponseBody
    public Dto login(@RequestParam String name, @RequestParam  String password, HttpServletRequest request){
        ItripUser user = userService.Login(name,password);
        password = Md5Util.getMd5(password,24);

        if (null == user){
            return DtoUtil.getFailed("不存在此用户，请检查用户名","103");
        }else if(!user.getUserPassword().equals(password)){
            return DtoUtil.getFailed("密码不正确，请检查密码","104");
        }else if (user.getActivated() == 0){
            return DtoUtil.getFailed("您的账号未激活，请先激活","105");
        }

        String token = tokenSevice.createToken(request.getHeader("user-agent"),user);
        tokenSevice.saveToken(token,user);
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(token);
        tokenVo.setExpTime(Calendar.getInstance().getTimeInMillis()+(TokenServiceImpl.MINUTE*60*1000));
        tokenVo.setGenTime(Calendar.getInstance().getTimeInMillis());

        return DtoUtil.getSuccess(tokenVo);
    }


    @ApiOperation(value = "用户注销")
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    @ResponseBody
    public Dto login(HttpServletRequest request){
        try {
            tokenSevice.deleteToken(request.getHeader("token"));
            return DtoUtil.getSuccess("您已退出登录");
        }catch (RuntimeException e){
            return DtoUtil.getFailed("注销失败","112");
        }
    }


    @ApiOperation(value = "验证置换token")
    @RequestMapping(value = "/retoken",method = RequestMethod.POST)
    @ResponseBody
    public Dto retoken(HttpServletRequest request){
            String agent = request.getHeader("user-agent");
            String token = request.getHeader("token");
        try {
            String newToken = tokenSevice.replaceToken(agent,token);
            TokenVo tokenVo = new TokenVo();
            tokenVo.setToken(newToken);
            tokenVo.setExpTime(TokenServiceImpl.MINUTE*60*1000);
            tokenVo.setGenTime(Calendar.getInstance().getTimeInMillis());
            return DtoUtil.getSuccess(tokenVo);

        } catch (ParseException e) {
            e.printStackTrace();
            return DtoUtil.getFailed(e.getMessage(),"112");
        }catch (RuntimeException e){
            return DtoUtil.getFailed(e.getMessage(),"113");
        }
    }

    @ApiOperation(value = "判断用户名是否存在")
    @RequestMapping(value = "/ckusr",method = RequestMethod.GET)
    @ResponseBody
    public Dto ckusr(@RequestParam String name){
        if (!userService.isRegist(name)){
            return DtoUtil.getSuccess("用户名可以使用");
        }else {
            return DtoUtil.getFailed("用户名已存在","114");
        }

    }



    //封装成对象
    private ItripUser regist(String userCode,String userPassword,String userName){
        ItripUser itripUser = new ItripUser();
        itripUser.setUserCode(userCode);
        itripUser.setUserPassword(userPassword);
        itripUser.setUserName(userName);
        return itripUser;
    }



}
